package org.jeecg.modules.product.risk.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.product.risk.entity.TbBaseControlMeasures;
import org.jeecg.modules.product.risk.entity.TbBaseDangerInvestigation;
import org.jeecg.modules.product.risk.entity.TbBaseMeasuresTask;
import org.jeecg.modules.product.risk.service.ITbBaseControlMeasuresService;
import org.jeecg.modules.product.risk.service.ITbBaseMeasuresTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import java.util.Arrays;
import org.jeecg.common.util.oConvertUtils;

import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 管控措施信息
 * @Author: jeecg-boot
 * @Date:   2024-04-25
 * @Version: V1.0
 */
@Tag(name="管控措施信息")
@RestController
@RequestMapping("/TbBaseControlMeasures/tbBaseControlMeasures")
@Slf4j
public class TbBaseControlMeasuresController extends JeecgController<TbBaseControlMeasures, ITbBaseControlMeasuresService> {

	@Autowired
	private ITbBaseControlMeasuresService tbBaseControlMeasuresService;

	@Autowired
	private ITbBaseMeasuresTaskService tbBaseMeasuresTaskService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param tbBaseControlMeasures
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "管控措施信息-分页列表查询")
	@Operation(summary="管控措施信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TbBaseControlMeasures>> queryPageList(TbBaseControlMeasures tbBaseControlMeasures,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
		QueryWrapper<TbBaseControlMeasures> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseControlMeasures, req.getParameterMap());
		Page<TbBaseControlMeasures> page = new Page<TbBaseControlMeasures>(pageNo, pageSize);
		IPage<TbBaseControlMeasures> pageList = tbBaseControlMeasuresService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 * @param tbBaseControlMeasures
	 * @return
	 */
	@AutoLog(value = "管控措施信息-添加")
	@Operation(summary="管控措施信息-添加")
	@RequiresPermissions("TbBaseControlMeasures:tb_base_control_measures:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TbBaseControlMeasures tbBaseControlMeasures) {
		tbBaseControlMeasuresService.save(tbBaseControlMeasures);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 * @param tbBaseControlMeasures
	 * @return
	 */
	@AutoLog(value = "管控措施信息-编辑")
	@Operation(summary="管控措施信息-编辑")
	@RequiresPermissions("TbBaseControlMeasures:tb_base_control_measures:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TbBaseControlMeasures tbBaseControlMeasures) {
		tbBaseControlMeasuresService.updateById(tbBaseControlMeasures);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "管控措施信息-通过id删除")
	@Operation(summary="管控措施信息-通过id删除")
	@RequiresPermissions("TbBaseControlMeasures:tb_base_control_measures:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		tbBaseControlMeasuresService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "管控措施信息-批量删除")
	@Operation(summary="管控措施信息-批量删除")
	@RequiresPermissions("TbBaseControlMeasures:tb_base_control_measures:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbBaseControlMeasuresService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 *   通过id逻辑删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-通过id逻辑删除")
	@Operation(summary="隐患排查信息-通过id逻辑删除")
	@DeleteMapping(value = "/logicDelete")
	public Result<?> logicDelete(@RequestParam(name="id",required=true) String id) {
		TbBaseControlMeasures entity = tbBaseControlMeasuresService.getById(id);
		//禁止状态1是已删除，0是正常未删除
		entity.setDeleted(CommonConstant.DEL_FLAG_1.toString());
		tbBaseControlMeasuresService.updateById(entity);
		return Result.OK("逻辑删除成功!");
	}

	/**
	 *  批量逻辑删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-批量逻辑删除")
	@Operation(summary="隐患排查信息-批量逻辑删除")
	@DeleteMapping(value = "/deleteLogicBatch")
	public Result<?> deleteLogicBatch(@RequestParam(name="ids",required=true) String ids) {
		List<TbBaseControlMeasures> list = tbBaseControlMeasuresService.listByIds(Arrays.asList(ids.split(",")));
		for (TbBaseControlMeasures entity : list) {
			entity.setDeleted(CommonConstant.DEL_FLAG_1.toString());
		}
		tbBaseControlMeasuresService.updateBatchById(list);
		return Result.OK("批量逻辑删除成功！");
	}

	/**
	 * 获取被逻辑删除
	 *
	 * @return
	 */
	@GetMapping("/recycleBin")
	public Result getRecycleBin() {
		QueryWrapper<TbBaseControlMeasures> queryWrapper = new QueryWrapper<>();
		//查询已经删除的数据
		queryWrapper.eq("deleted", CommonConstant.DEL_FLAG_1.toString());
		List<TbBaseControlMeasures> list = tbBaseControlMeasuresService.list(queryWrapper);
		return Result.ok(list);
	}

	/**
	 * 还原被逻辑删除
	 *
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
	public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
		String ids = jsonObject.getString("ids");
		if (StringUtils.isNotBlank(ids)) {
			List<TbBaseControlMeasures> list = tbBaseControlMeasuresService.listByIds(Arrays.asList(ids.split(",")));
			for (TbBaseControlMeasures entity : list) {
				entity.setDeleted(CommonConstant.DEL_FLAG_0.toString());
			}
			tbBaseControlMeasuresService.updateBatchById(list);
		}
		return Result.ok("还原成功");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequiresPermissions("TbBaseControlMeasures:tb_base_control_measures:exportXls")
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, TbBaseControlMeasures tbBaseControlMeasures) {
		return super.exportXls(request, tbBaseControlMeasures, TbBaseControlMeasures.class, "管控措施信息");
	}

	/**
	 * 导入
	 * @return
	 */
	@RequiresPermissions("TbBaseControlMeasures:tb_base_control_measures:importExcel")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, TbBaseControlMeasures.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/


	/*--------------------------------子表处理-隐患排查任务信息-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "隐患排查任务信息-通过主表ID查询")
	@Operation(summary="隐患排查任务信息-通过主表ID查询")
	@GetMapping(value = "/listTbBaseMeasuresTaskByMainId")
	public Result<IPage<TbBaseMeasuresTask>> listTbBaseMeasuresTaskByMainId(TbBaseMeasuresTask tbBaseMeasuresTask,
																			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
																			HttpServletRequest req) {
		QueryWrapper<TbBaseMeasuresTask> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseMeasuresTask, req.getParameterMap());
		Page<TbBaseMeasuresTask> page = new Page<TbBaseMeasuresTask>(pageNo, pageSize);
		IPage<TbBaseMeasuresTask> pageList = tbBaseMeasuresTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 * @param tbBaseMeasuresTask
	 * @return
	 */
	@AutoLog(value = "隐患排查任务信息-添加")
	@Operation(summary="隐患排查任务信息-添加")
	@PostMapping(value = "/addTbBaseMeasuresTask")
	public Result<String> addTbBaseMeasuresTask(@RequestBody TbBaseMeasuresTask tbBaseMeasuresTask) {
		tbBaseMeasuresTaskService.save(tbBaseMeasuresTask);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 * @param tbBaseMeasuresTask
	 * @return
	 */
	@AutoLog(value = "隐患排查任务信息-编辑")
	@Operation(summary="隐患排查任务信息-编辑")
	@RequestMapping(value = "/editTbBaseMeasuresTask", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editTbBaseMeasuresTask(@RequestBody TbBaseMeasuresTask tbBaseMeasuresTask) {
		tbBaseMeasuresTaskService.updateById(tbBaseMeasuresTask);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "隐患排查任务信息-通过id删除")
	@Operation(summary="隐患排查任务信息-通过id删除")
	@DeleteMapping(value = "/deleteTbBaseMeasuresTask")
	public Result<String> deleteTbBaseMeasuresTask(@RequestParam(name="id",required=true) String id) {
		tbBaseMeasuresTaskService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "隐患排查任务信息-批量删除")
	@Operation(summary="隐患排查任务信息-批量删除")
	@DeleteMapping(value = "/deleteBatchTbBaseMeasuresTask")
	public Result<String> deleteBatchTbBaseMeasuresTask(@RequestParam(name="ids",required=true) String ids) {
		this.tbBaseMeasuresTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportTbBaseMeasuresTask")
	public ModelAndView exportTbBaseMeasuresTask(HttpServletRequest request, TbBaseMeasuresTask tbBaseMeasuresTask) {
		// Step.1 组装查询条件
		QueryWrapper<TbBaseMeasuresTask> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseMeasuresTask, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<TbBaseMeasuresTask> pageList = tbBaseMeasuresTaskService.list(queryWrapper);
		List<TbBaseMeasuresTask> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, "隐患排查任务信息");
		mv.addObject(NormalExcelConstants.CLASS, TbBaseMeasuresTask.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("隐患排查任务信息报表", "导出人:" + sysUser.getRealname(), "隐患排查任务信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importTbBaseMeasuresTask/{mainId}")
	public Result<?> importTbBaseMeasuresTask(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<TbBaseMeasuresTask> list = ExcelImportUtil.importExcel(file.getInputStream(), TbBaseMeasuresTask.class, params);
				for (TbBaseMeasuresTask temp : list) {
					temp.setRiskMeasureId(mainId);
				}
				long start = System.currentTimeMillis();
				tbBaseMeasuresTaskService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-隐患排查任务信息-end----------------------------------------------*/




}
